package com.nbsaas.boot.lock.impl;

import com.nbsaas.boot.lock.api.LockService;

import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicBoolean;

public class ConcurrentHashMapLockService implements LockService {

    private final ConcurrentHashMap<String, AtomicBoolean> lockMap = new ConcurrentHashMap<>();

    @Override
    public boolean lock(String key) {
        return false;
    }

    @Override
    public boolean lock(String key, long timeout, TimeUnit unit) {
        AtomicBoolean lockState = lockMap.computeIfAbsent(key, k -> new AtomicBoolean(false));
        long timeoutMillis = unit.toMillis(timeout);
        long startTime = System.currentTimeMillis();

        while (System.currentTimeMillis() - startTime < timeoutMillis) {
            if (lockState.compareAndSet(false, true)) {
                return true;  // 成功获取锁
            }
            try {
                Thread.sleep(10);  // 重试间隔
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
                return false;
            }
        }
        return false;  // 超时未获取到锁
    }

    @Override
    public boolean unlock(String key) {
        AtomicBoolean lockState = lockMap.get(key);
        if (lockState != null) {
            lockState.set(false);  // 释放锁
            return true;
        }
        return false;
    }

    @Override
    public boolean isLocked(String key) {
        AtomicBoolean lockState = lockMap.get(key);
        return lockState != null && lockState.get();
    }
}
